package org.shagin.jfin.ui;

import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.jdesktop.application.Application.KEY_APPLICATION_ICON;
import static org.jdesktop.application.Application.KEY_APPLICATION_TITLE;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Image;

import org.jdesktop.application.FrameView;
import org.jdesktop.application.ResourceMap;
import org.shagin.jfin.core.ui.JJFrame;
import org.shagin.jfin.core.ui.UIUtils;
import org.shagin.jfin.ui.actions.MainFrameActions;
import org.shagin.jfin.ui.sheet.SheetTableView;

/**
 * The Class MainWindow.
 */
@SuppressWarnings("serial")
public class JMainFrame extends JJFrame {

    private static JMainFrame instance = null;

    private MainFrameMenu menu;
    private SheetTableView sheetTable;
    private MainFrameActions actions = new MainFrameActions(this);

    /**
     * Instantiates a new main window.
     */
    private JMainFrame() {
        super();
        setName(FrameView.MAIN_FRAME_NAME);
        ResourceMap resourceMap = getContext().getResourceMap();

        String title = resourceMap.getString(KEY_APPLICATION_TITLE);
        if (!isEmpty(title))
            setTitle(title);
        setName(FrameView.MAIN_FRAME_NAME);
        if (resourceMap.containsKey(KEY_APPLICATION_ICON)) {
            Image icon = resourceMap.getImageIcon(KEY_APPLICATION_ICON)
                    .getImage();
            setIconImage(icon);
        }

        setup();
        runDefferedInit();
    }

    /**
     * Jb init.
     */
    public void jbInit() {
        Container pane = getContentPane();
        pane.setLayout(new BorderLayout());
        sheetTable = new SheetTableView();
        pane.add(sheetTable, BorderLayout.CENTER);
        buildMenu();
    }

    /**
     * Setup.
     */
    private void setup() {
        jbInit();
        pack();
    }

    /**
     * Builds the menu.
     * 
     * @param sheetTable the sheet table
     */
    private void buildMenu() {
        menu = new MainFrameMenu(this);
        setJMenuBar(menu.getMenuBar());
    }

    /**
     * Gets the single instance of MainWindow.
     * 
     * @return single instance of MainWindow
     */
    public static JMainFrame getInstance() {
        if (instance == null)
            instance = new JMainFrame();
        return instance;
    }

    /**
     * Run deffered init.
     */
    private void runDefferedInit() {
        UIUtils.runDeffredAction(new Runnable() {
            @Override
            public void run() {
                actions.refreshBudget();
            }
        });
    }

    /**
     * Gets the sheet table.
     *
     * @return the sheet table
     */
    public SheetTableView getSheetTable() {
        return sheetTable;
    }

    /**
     * Gets the actions.
     *
     * @return the actions
     */
    public MainFrameActions getActions() {
        return actions;
    }
}
